package com.smedi.ismedi.web.starter.config;

import com.smedi.ismedi.authority.starter.common.ResponseData;
import com.smedi.ismedi.authority.starter.exception.ErrorItem;
import com.smedi.ismedi.authority.starter.exception.LogicException;
import com.smedi.ismedi.authority.starter.util.JsonHelper;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 拦截Feign的Exception，并抓取服务端的错误消息
 * 需要底层服务不封装Exception
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class FeignGlobalExceptionConfig implements ErrorDecoder {
    private final JsonHelper jsonHelper;

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        try {
            String json = Util.toString(response.body().asReader(Charset.defaultCharset()));
            exception = new RuntimeException(json);
            ResponseData responseData = jsonHelper.jsonToObject(json, ResponseData.class);
            if (!responseData.isSuccess()) {
                exception = new LogicException(ErrorItem.builder().code(Integer.parseInt(responseData.getCode())).message(String.valueOf(responseData.getErrorMsg())).build());
            }
        } catch (IOException e) {
            return e;
        }

//        String body = null;
//        try {
//            body = Util.toString(response.body().asReader(Charset.defaultCharset()));
//            // log.info("body >>> {}", body);
//        } catch (IOException e) {
//            // log.info("IOException >>> {} {}", e.getMessage());
//            return e;
//        }

//        if (response.status() >= 400 && response.status() <= 500) {
//            log.info("FeignGlobalExceptionConfig response.status >>> {}", response.status());
//            if (response.status() == 401) {
//                ResponseData<Void> responseData = JSON.parseObject(body, ResponseData.class);
//                // 解决如果在Bff层的抛错会被重置为200的情况
//                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//                request.getSession().setAttribute(AuthorityConstant.code401, true);
//
//                RuntimeException runtimeException = new RuntimeException(responseData.getErrorMsg().toString());
//                return runtimeException;
//            } else {
//
//                /**
//                 * 如果转换成exception，则会将整个RuntimeException封装
//                 * 到Exception中，故不适用。*/
//                Exception exception = JSON.parseObject(body, RuntimeException.class);
//                return exception;
//            }
//        }
//        FeignException feignException = errorStatus(methodKey, response);
//        log.error("FeignGlobalException:{}", feignException.getMessage(), feignException);

        return exception;
    }
}
